package com.peking.donations.base.dao;

import com.peking.donations.base.model.BaseModelAuditable;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import java.io.Serializable;
import java.util.Date;

public class HibernateInterceptor extends EmptyInterceptor {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4526345134917597028L;

	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		if (entity instanceof BaseModelAuditable) {
			Date now = new Date();
			setCreatedDate(state, propertyNames, now);
			setLastUpdated(state, propertyNames, now);
			return true;
		}
		return false;
	}

	@Override
	public boolean onFlushDirty(Object entity, Serializable id, Object[] state,
			Object[] previousState, String[] propertyNames, Type[] types) {
		if (entity instanceof BaseModelAuditable) {
			setLastUpdated(state, propertyNames, new Date());
			return true;
		}
		return false;
	}

	private void setCreatedDate(Object[] state, String[] propertyNames,
			Date date) {
		for (int i = 0; i < propertyNames.length; i++) {
			if ("createdAt".equals(propertyNames[i])) {
				state[i] = date;
			}
		}
	}

	private void setLastUpdated(Object[] state, String[] propertyNames,
			Date date) {
		for (int i = 0; i < propertyNames.length; i++) {
			if ("updatedAt".equals(propertyNames[i])) {
				state[i] = date;
			}
		}
	}
}
